// 配置管理组合式函数
import { ref, computed, onMounted } from 'vue'
import configService from '../services/configService.js'

// 全局配置状态
const globalConfig = ref(null)
const configLoading = ref(false)
const configError = ref(null)

export function useConfig() {
  // 加载配置
  const loadConfig = async () => {
    if (globalConfig.value) {
      return globalConfig.value
    }

    configLoading.value = true
    configError.value = null

    try {
      const config = await configService.getConfig()
      globalConfig.value = config
      console.log('配置加载完成:', config)
      return config
    } catch (error) {
      console.error('配置加载失败:', error)
      configError.value = error
      throw error
    } finally {
      configLoading.value = false
    }
  }

  // 重新加载配置
  const reloadConfig = async () => {
    configService.clearCache()
    globalConfig.value = null
    return await loadConfig()
  }

  // 计算属性
  const grades = computed(() => globalConfig.value?.grades || [])
  const difficulties = computed(() => globalConfig.value?.difficulties || [])
  const subjects = computed(() => globalConfig.value?.subjects || [])
  const knowledgePoints = computed(() => globalConfig.value?.knowledgePoints || {})
  const questionTypes = computed(() => globalConfig.value?.questionTypes || [])
  const maxQuestions = computed(() => globalConfig.value?.maxQuestions || 50)

  // 工具方法
  const getGradeLevel = (grade) => {
    if (!grade) return '小学'
    if (grade.includes('小学')) return '小学'
    if (grade.includes('初')) return '初中'
    if (grade.includes('高')) return '高中'
    return '小学'
  }

  const getKnowledgePointsBySubjectAndGrade = (subject, grade) => {
    if (!subject || !grade || !knowledgePoints.value[subject]) {
      return []
    }
    
    const gradeLevel = getGradeLevel(grade)
    return knowledgePoints.value[subject][gradeLevel] || []
  }

  const getQuestionTypeOptions = () => {
    return {
      choice: { key: 'choice', label: '选择题', maxCount: 20 },
      fill: { key: 'fill', label: '填空题', maxCount: 20 },
      answer: { key: 'answer', label: '解答题', maxCount: 10 }
    }
  }

  const getScoreMap = () => {
    return {
      choice: 3,
      fill: 4,
      answer: 8
    }
  }

  const getDefaultConfig = () => {
    return {
      grade: '初一',
      difficulty: '中等',
      subject: '数学',
      knowledgePoints: ['有理数'],
      questionTypes: {
        choice: { enabled: true, count: 15 },
        fill: { enabled: true, count: 10 },
        answer: { enabled: true, count: 5 }
      }
    }
  }

  return {
    // 状态
    globalConfig,
    configLoading,
    configError,

    // 计算属性
    grades,
    difficulties,
    subjects,
    knowledgePoints,
    questionTypes,
    maxQuestions,

    // 方法
    loadConfig,
    reloadConfig,
    getGradeLevel,
    getKnowledgePointsBySubjectAndGrade,
    getQuestionTypeOptions,
    getScoreMap,
    getDefaultConfig
  }
}